package resource

import (
	"awesomeTask/application/models/taskLog"
	"awesomeTask/application/task/RunningTask"
	"awesomeTask/application/variable"
	"awesomeTask/commom/timeHelper"
	"awesomeTask/config"
	"awesomeTask/system/helper"
	"awesomeTask/system/kernel"
	"awesomeTask/system/log"
	"bufio"
	"encoding/base64"
	"fmt"
	"strings"
)

// 创建python 虚拟环境
func getEnvPath(projectName string) string {
	return config.GetConfigByKey("projectPath").(string) + projectName + "/venv/"
}
func GetProjectPath(projectName string) string {
	return config.GetConfigByKey("projectPath").(string) + projectName + "/"
}
func getScriptName(projectName string) string {
	if kernel.IsLinux() == false {
		return getEnvPath(projectName) + "/Scripts/"
	} else {
		return getEnvPath(projectName) + "/bin/"
	}

}
func PythonEnv(projectName string) {
	projectPath := getEnvPath(projectName)
	res, _ := helper.PathExists(projectPath)
	if res {
		return
	}
	kernel.GetKernelDriver().ExceShellOrBash(GetPythonCommand()+"-m venv "+projectPath, true)
	log.GetLogger().Warn("构建pythonEnv" + GetPythonCommand() + "-m venv " + projectPath)
	initAwesomeTask(projectName)
}

//发布Python的依赖
func PythonDependence(projectName string, packetData []byte) {

}
func PipCommad(projectName string, command string) {
	kernel.GetKernelDriver().ExceShellOrBash(getScriptName(projectName)+"pip "+command, true)
}
func InstallPacket(packetName string, projectName string) {
	PipCommad(projectName, "config set global.index-url https://pypi.Python.org/simple/") //换源
	PipCommad(projectName, "install "+packetName)
}
func initAwesomeTask(projectName string) {
	InstallPacket("awesomeTaskPy", projectName) //初始化python任务执行包
	template := `
from awesomeTaskPy.context import context
from awesomeTaskPy.task.baseTask import baseTask
if __name__ == '__main__':
    context.initContext()
    baseTask(context.getContext().getTaskInfo(),context.getContext().getTaskInfo()["module"])

` //初始化入口文件
	helper.WriteFile(GetProjectPath(projectName)+"main.py", template, 0777)
	//初始化项目入口
	helper.Mkdir(GetProjectPath(projectName)+variable.ApplicationPath, 0777)
}
func getRunningInfo(projectName string, taskId string) string {
	logPath := GetProjectPath(projectName) + "/runtime/" + taskId + "/result.log"
	logPath = strings.ReplaceAll(logPath, "//", "/")
	exits, err := helper.PathExists(logPath)
	if err != nil || !exits {
		return `{"startAt":"1970-01-01 00:00:00" , "endAt": "1970-01-01 00:00:00", "runTime": 0, "result": null, "error": "程序异常执行节点未能捕获异常"}`
	}
	return helper.ReadFileAsString(logPath)

}
func GetPythonCommand() string {
	return config.GetConfigByKey("pythonCommand", func() interface{} {
		return "python"
	}).(string) + " -u "
}
func RunTask(projectPath string, params map[string]interface{}, taskId string) RunningTask.RunTaskProcess {
	PythonEnv(projectPath)
	interpreterPath := getScriptName(projectPath) + GetPythonCommand()
	mainPath := GetProjectPath(projectPath) + "main.py"
	//helper.WriteFile(GetProjectPath(projectPath)+"/input/"+taskId+"/input.log", params, 0777)
	paramsString := base64.StdEncoding.EncodeToString([]byte(helper.JsonEncode(helper.JsonEncode(params))))
	log.GetLogger().Info("commad===>" + interpreterPath + " " + mainPath + " " + paramsString)
	c := kernel.GetKernelDriver().ExceShellOrBashAysn(interpreterPath + " " + mainPath + " " + paramsString)
	logId := taskLog.CreateLog(taskId, config.GetConfigByKey("uniqueId").(string), helper.JsonEncode(params), 1)
	runningTask := RunningTask.RunTaskProcess{
		TaskId:    taskId,
		TaskLogId: logId,
		Stdout:    &kernel.StdWriter{},
		Stderr:    &kernel.StdWriter{},
		Cmd:       c,
		StartAt:   timeHelper.NowInt(),
	}
	//c.Stdout = runningTask.Stdout
	//c.Stderr = runningTask.Stderr
	//instance := kernel.GetIocInstance()
	//taskManager:=instance.GetInstanceOrCreate("runningTaskManager").(*RunningTask.RunningTask)
	//instance.CallFunByName(taskManager,"PushRunningTask",runningTask)
	pipe, err := c.StdoutPipe()
	c.Start()
	if err != nil {
		panic(err.Error())
	}
	go func() {
		for true {
			r := bufio.NewReader(pipe)
			line, _, err := r.ReadLine()
			if err != nil {
				break
			}
			fmt.Println(line, "line=========>")
			fmt.Println(err, "err===========>")
		}
	}()
	c.Wait()
	//instance.CallFunByName(taskManager,"EndTask",runningTask)
	fmt.Println("end===========>")
	return runningTask
}
func InstallMany(projectName string, packge []map[string]interface{}) {
	for _, item := range packge {
		if item["version"].(string) == "" {
			InstallPacket(projectName, item["packge"].(string))
		} else {
			InstallPacket(projectName, item["packge"].(string)+"="+item["version"].(string))
		}

	}
}
